import {CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM, INIT_LIST_ITEM} from './actionTypes';

// 默认值
const defaultState = {
    inputValue: '',
    list: []
};

// reducer可以接收state, 绝不可以修改state, 所以深拷贝一份state做修改

// reducer必须是 纯函数(给固定的输入,必有固定的输出,而且无任何副作用)

export default (state = defaultState, action) => {
    // console.log(state,action) //state 之前的数据 , action 要做的事

    if(action.type === CHANGE_INPUT_VALUE){
        // 深拷贝、浅拷贝
        const newState = JSON.parse(JSON.stringify(state));
        newState.inputValue = action.value;
        return newState;
    }

    if(action.type === ADD_TODO_ITEM){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.push(newState.inputValue);
        newState.inputValue = '';
        return newState;
    }

    if(action.type === DELETE_TODO_ITEM){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.splice(action.index,1);
        return newState;
    }

    if(action.type === INIT_LIST_ITEM){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list = action.data;
        return newState;
    }

    return state;
}